<script setup>
import { reactive, ref } from 'vue';
import axios from 'axios';

// 从 vue-router 中导入 useRouter 函数
import { useRouter } from 'vue-router';
// 获得用于导航的对象(即路由器)
const router = useRouter();

import { useLoginedStore } from '@/stores/logined';
// 从当前应用中获取 loginedStore
const loginedStore = useLoginedStore();

// 用来在页面上显示提示信息的
const tip = ref('');

const userInfos = reactive({
    email: '',
    password: '',
});

const emailRules = [
    { required: true, message: '请输入电子邮箱' }
];
const pwdRules = [
    { required: true, message: '请输入登录密码' }
];
const login = (values) => {
  console.log('Success:', values);
  const url = '/back/user/sign/in';
  const data = {
    email: values.email,
    password: values.password
  }
  // 通过 axios 发送 POST 请求
  axios.post(url, data).then(response => {
    console.log( response.data );
    // ECMA Script 2015 提供的 解构赋值
    const { success, message, token } = response.data;
    console.log( response.data );
    if( success ) {
        // 调用 loginedStore 中的 Action 完成登录操作
        loginedStore.set(token);
        router.push( '/home/list' )
        return;
    }
    // 将后端返回的提示信息赋值给 tip 以便于 Vue 在页面上展示
    tip.value = message;
  }).catch(error => {
    console.log( error );
  })
};

const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo);
};
</script>

<template>
    <div class="login">
        <h1>用户登录</h1>
        <div>{{ tip }}</div>
        <a-form :model="userInfos"
                :label-col="{ span: 4 }" 
                :wrapper-col="{ span: 16 }"
                autocomplete="off"
                @finish="login"
                @finishFailed="onFinishFailed">
            <a-form-item label="邮箱" name="email" :rules="emailRules">
                <a-input v-model:value="userInfos.email"/>
            </a-form-item>
            <a-form-item label="登录密码" name="password" :rules="pwdRules">
                <a-input-password v-model:value="userInfos.password"/>
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
                <a-button type="primary" html-type="submit">登录</a-button>
            </a-form-item>
        </a-form>
        <p>
            <router-link to="/register" class="link">注册</router-link>
        </p>
    </div>
</template>

<style scoped>
.login {
    margin-top: 20vh;
    margin-left: 25vw;
    width: 50vw;
}
h1,
p,
div{
    text-align: center;
}
</style>